<template>
  <div class="normal-admin-container">
    <el-header class="header">
      <div class="header-left">
        <h2>普通管理员系统</h2>
      </div>
      <div class="header-right">
        <span class="welcome">欢迎，{{ adminInfo.realName }}</span>
        <el-button type="danger" @click="handleLogout">退出登录</el-button>
      </div>
    </el-header>

    <el-main class="main-content">
      <!-- 标签页切换 -->
      <el-tabs v-model="activeTab" class="admin-tabs">

        <el-tab-pane label="医生管理" name="doctors">
          <!-- 医生管理内容 -->
          <div class="tab-content">
            <!-- 搜索和操作区域 -->
            <div class="toolbar">
              <div class="search-area">
                <el-input
                  v-model="doctorSearchForm.realName"
                  placeholder="医生姓名"
                  style="width: 150px; margin-right: 10px"
                  clearable
                />
                <el-input
                  v-model="doctorSearchForm.phone"
                  placeholder="联系电话"
                  style="width: 150px; margin-right: 10px"
                  clearable
                />
                <el-input
                  v-model="doctorSearchForm.email"
                  placeholder="电子邮箱"
                  style="width: 180px; margin-right: 10px"
                  clearable
                />
                <el-select
                  v-model="doctorSearchForm.gender"
                  placeholder="性别"
                  style="width: 120px; margin-right: 10px"
                  clearable
                >
                  <el-option label="男" :value="1" />
                  <el-option label="女" :value="2" />
                </el-select>
                <el-input
                  v-model="doctorSearchForm.practiceScope"
                  placeholder="执业范围"
                  style="width: 150px; margin-right: 10px"
                  clearable
                />
                <el-select
                  v-model="doctorSearchForm.level"
                  placeholder="等级"
                  style="width: 120px; margin-right: 10px"
                  clearable
                >
                  <el-option label="Lv.1" :value="1" />
                  <el-option label="Lv.2" :value="2" />
                  <el-option label="Lv.3" :value="3" />
                  <el-option label="Lv.4" :value="4" />
                  <el-option label="Lv.5" :value="5" />
                  <el-option label="Lv.6" :value="6" />
                  <el-option label="Lv.7" :value="7" />
                  <el-option label="Lv.8" :value="8" />
                  <el-option label="Lv.9" :value="9" />
                  <el-option label="Lv.10" :value="10" />
                </el-select>
                <el-select
                  v-model="doctorSearchForm.hospitalName"
                  placeholder="医院名称"
                  style="width: 200px; margin-right: 10px"
                  clearable
                >
                  <el-option 
                    v-for="hospital in hospitalList" 
                    :key="hospital" 
                    :label="hospital" 
                    :value="hospital" 
                  />
                </el-select>
                <el-button type="primary" @click="handleDoctorSearch">搜索</el-button>
                <el-button @click="resetDoctorSearch">重置</el-button>
              </div>
              
              <div class="action-area">
                <el-button type="success" @click="showCreateDoctorDialog">新增医生</el-button>
                <el-button type="warning" @click="showDeletedDoctors">查看已删除医生</el-button>
                <el-button type="danger" @click="handleBatchDeleteDoctor" :disabled="!selectedDoctors.length">
                  批量删除
                </el-button>
              </div>
            </div>

            <!-- 医生数据表格 -->
            <el-table
              :data="doctorList"
              @selection-change="handleDoctorSelectionChange"
              v-loading="doctorLoading"
              border
              style="width: 100%"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column prop="id" label="ID" width="80" />
              <el-table-column prop="username" label="用户名" width="120" />
              <el-table-column prop="realName" label="医生姓名" width="120" />
              <el-table-column prop="phone" label="联系电话" width="130" />
              <el-table-column prop="email" label="电子邮箱" width="180" />
              <el-table-column prop="gender" label="性别" width="80">
                <template #default="{ row }">
                  <el-tag :type="row.gender === 1 ? 'primary' : row.gender === 2 ? 'success' : 'info'">
                    {{ row.gender === 1 ? '男' : row.gender === 2 ? '女' : '未设置' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="practiceScope" label="执业范围" width="120">
                <template #default="{ row }">
                  {{ row.practiceScope || '未设置' }}
                </template>
              </el-table-column>
              <el-table-column prop="hospitalName" label="所属医院" width="180">
                <template #default="{ row }">
                  {{ row.hospitalName || '未设置' }}
                </template>
              </el-table-column>
              <el-table-column prop="points" label="积分" width="80">
                <template #default="{ row }">
                  {{ row.points }}
                </template>
              </el-table-column>
              <el-table-column prop="createTime" label="创建时间" width="160">
                <template #default="{ row }">
                  {{ formatDateTime(row.createTime) }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="280" fixed="right">
                <template #default="{ row }">
                  <el-button type="primary" size="small" @click="showEditDoctorDialog(row)">
                    编辑
                  </el-button>
                  <el-button type="danger" size="small" @click="handleDeleteDoctor(row)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- 医生分页 -->
            <div class="pagination">
              <el-pagination
                v-model:current-page="doctorPagination.current"
                v-model:page-size="doctorPagination.size"
                :page-sizes="[10, 20, 50, 100]"
                :total="doctorPagination.total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleDoctorSizeChange"
                @current-change="handleDoctorCurrentChange"
              />
            </div>
          </div>
        </el-tab-pane>

        <el-tab-pane label="活动管理" name="activities">
          <!-- 活动管理内容 -->
          <div class="tab-content">
            <!-- 搜索和操作区域 -->
            <div class="toolbar">
              <div class="search-area">
                <el-input
                  v-model="activitySearchForm.name"
                  placeholder="活动名称"
                  style="width: 200px; margin-right: 10px"
                  clearable
                />
                <el-input
                  v-model="activitySearchForm.location"
                  placeholder="活动地点"
                  style="width: 200px; margin-right: 10px"
                  clearable
                />
                <el-date-picker
                  v-model="activitySearchForm.startTime"
                  type="datetime"
                  placeholder="开始时间"
                  style="width: 180px; margin-right: 10px"
                  clearable
                />
                <el-date-picker
                  v-model="activitySearchForm.endTime"
                  type="datetime"
                  placeholder="结束时间"
                  style="width: 180px; margin-right: 10px"
                  clearable
                />
                <el-button type="primary" @click="handleActivitySearch">搜索</el-button>
                <el-button @click="resetActivitySearch">重置</el-button>
              </div>
              
              <div class="action-area">
                <el-button type="success" @click="showCreateActivityDialog">新增活动</el-button>
                <el-button type="danger" @click="handleBatchDeleteActivity" :disabled="!selectedActivities.length">
                  批量删除
                </el-button>
              </div>
            </div>

            <!-- 活动数据表格 -->
            <el-table
              :data="activityList"
              @selection-change="handleActivitySelectionChange"
              v-loading="activityLoading"
              border
              style="width: 100%"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column prop="id" label="ID" width="80" />
              <el-table-column prop="name" label="活动名称" width="200" />
              <el-table-column prop="cover" label="封面图片" width="120">
                <template #default="{ row }">
                  <div v-if="row.cover" style="position: relative;">
                    <el-image
                      :src="processCoverUrl(row.cover)"
                      style="width: 80px; height: 60px"
                      fit="cover"
                      :preview-src-list="[processCoverUrl(row.cover)]"
                      @error="handleImageError"
                    />
                    <span class="image-error" style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); color: #999; display: none;">加载失败</span>
                  </div>
                  <span v-else>无图片</span>
                </template>
              </el-table-column>
              <el-table-column prop="description" label="活动描述" width="300" show-overflow-tooltip />
              <el-table-column prop="location" label="活动地点" width="150" />
              <el-table-column prop="startTime" label="开始时间" width="160">
                <template #default="{ row }">
                  {{ formatDateTime(row.startTime) }}
                </template>
              </el-table-column>
              <el-table-column prop="endTime" label="结束时间" width="160">
                <template #default="{ row }">
                  {{ formatDateTime(row.endTime) }}
                </template>
              </el-table-column>
              <el-table-column prop="createdAt" label="创建时间" width="160">
                <template #default="{ row }">
                  {{ formatDateTime(row.createdAt) }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="200" fixed="right">
                <template #default="{ row }">
                  <el-button type="primary" size="small" @click="showEditActivityDialog(row)">
                    编辑
                  </el-button>
                  <el-button type="danger" size="small" @click="handleDeleteActivity(row)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- 活动分页 -->
            <div class="pagination">
              <el-pagination
                v-model:current-page="activityPagination.current"
                v-model:page-size="activityPagination.size"
                :page-sizes="[10, 20, 50, 100]"
                :total="activityPagination.total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleActivitySizeChange"
                @current-change="handleActivityCurrentChange"
              />
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-main>

    <!-- 医生新增/编辑对话框 -->
    <el-dialog
      v-model="doctorDialogVisible"
      :title="doctorDialogTitle"
      width="600px"
      @close="resetDoctorForm"
    >
      <el-form
        ref="doctorFormRef"
        :model="doctorForm"
        :rules="doctorFormRules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username" v-if="!isEditDoctor">
          <el-input v-model="doctorForm.username" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!isEditDoctor">
          <el-input v-model="doctorForm.password" type="password" show-password />
        </el-form-item>
        <el-form-item label="医生姓名" prop="realName">
          <el-input v-model="doctorForm.realName" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="doctorForm.phone" />
        </el-form-item>
        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="doctorForm.email" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="doctorForm.gender" style="width: 100%">
            <el-option label="男" :value="1" />
            <el-option label="女" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="家庭住址" prop="address">
          <el-input v-model="doctorForm.address" />
        </el-form-item>
        <el-form-item label="执业范围" prop="practiceScope">
          <el-input v-model="doctorForm.practiceScope" />
        </el-form-item>
        <el-form-item label="所属医院" prop="hospitalName">
          <el-select v-model="doctorForm.hospitalName" style="width: 100%">
            <el-option 
              v-for="hospital in hospitalList" 
              :key="hospital" 
              :label="hospital" 
              :value="hospital" 
            />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="doctorDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleDoctorSubmit" :loading="doctorSubmitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 已删除医生对话框 -->
    <el-dialog
      v-model="deletedDoctorsDialogVisible"
      title="已删除医生管理"
      width="1200px"
      @close="deletedDoctorsPagination.current = 1"
    >
      <div class="deleted-doctors-content">
        <!-- 已删除医生表格 -->
        <el-table
          :data="deletedDoctorsList"
          v-loading="deletedDoctorsLoading"
          border
          style="width: 100%"
        >
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="username" label="用户名" width="120" />
          <el-table-column prop="realName" label="医生姓名" width="120" />
          <el-table-column prop="phone" label="联系电话" width="130" />
          <el-table-column prop="email" label="邮箱" width="180" />
          <el-table-column prop="gender" label="性别" width="80">
            <template #default="{ row }">
              <el-tag :type="row.gender === 1 ? 'primary' : row.gender === 2 ? 'success' : 'info'">
                {{ row.gender === 1 ? '男' : row.gender === 2 ? '女' : '未知' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="practiceScope" label="执业范围" width="120" />
          <el-table-column prop="level" label="等级" width="80">
            <template #default="{ row }">
              Lv.{{ row.level }}
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="160">
            <template #default="{ row }">
              {{ formatDateTime(row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="deleteTime" label="删除时间" width="160">
            <template #default="{ row }">
              {{ formatDateTime(row.deleteTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" fixed="right">
            <template #default="{ row }">
              <el-button type="success" size="small" @click="handleRestoreDoctor(row.id)">
                恢复
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 已删除医生分页 -->
        <div class="pagination">
          <el-pagination
            v-model:current-page="deletedDoctorsPagination.current"
            v-model:page-size="deletedDoctorsPagination.size"
            :page-sizes="[10, 20, 50, 100]"
            :total="deletedDoctorsPagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleDeletedDoctorsSizeChange"
            @current-change="handleDeletedDoctorsCurrentChange"
          />
        </div>
      </div>
    </el-dialog>



    <!-- 活动新增/编辑对话框 -->
    <el-dialog
      v-model="activityDialogVisible"
      :title="activityDialogTitle"
      width="800px"
      @close="resetActivityForm"
    >
      <el-form
        ref="activityFormRef"
        :model="activityForm"
        :rules="activityFormRules"
        label-width="120px"
      >
        <el-form-item label="活动名称" prop="name">
          <el-input v-model="activityForm.name" placeholder="请输入活动名称" />
        </el-form-item>
        <el-form-item label="封面图片" prop="cover">
          <div class="cover-upload">
            <el-upload
              ref="coverUploadRef"
              :auto-upload="false"
              :show-file-list="false"
              :on-change="handleCoverChange"
              accept="image/*"
              class="cover-uploader"
            >
              <img v-if="activityForm.cover" :src="activityForm.cover" class="cover-image" />
              <el-icon v-else class="cover-uploader-icon"><Plus /></el-icon>
            </el-upload>
            <div class="cover-tips">
              <p>支持 jpg, jpeg, png, gif, bmp 格式</p>
              <p>文件大小不超过 5MB</p>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="活动描述" prop="description">
          <el-input
            v-model="activityForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入活动描述"
          />
        </el-form-item>

        <el-form-item label="活动地点" prop="location">
          <el-input v-model="activityForm.location" placeholder="请输入活动地点" />
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="activityForm.startTime"
            type="datetime"
            placeholder="选择开始时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="activityForm.endTime"
            type="datetime"
            placeholder="选择结束时间"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="activityDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleActivitySubmit" :loading="activitySubmitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

import { 
  getDoctorsByAdmin, 
  createDoctor, 
  updateDoctor, 
  deleteDoctor, 
  batchDeleteDoctor,
  getDeletedDoctorsPage,
  restoreDoctor
} from '../api/doctor'
import { getHospitalList } from '../api/admin'
import { 
  getAdminActivityList, 
  createActivity, 
  updateActivity, 
  deleteActivity,
  uploadActivityCover
} from '../api/activity'

const router = useRouter()
const activeTab = ref('doctors')

// 医生管理相关
const doctorLoading = ref(false)
const doctorList = ref([])
const selectedDoctors = ref([])
const doctorDialogVisible = ref(false)
const isEditDoctor = ref(false)
const doctorSubmitLoading = ref(false)
const doctorFormRef = ref()
const hospitalList = ref([])

const doctorSearchForm = reactive({
  realName: '',
  phone: '',
  email: '',
  gender: '',
  practiceScope: '',
  level: '',
  hospitalName: ''
})

const doctorForm = reactive({
  username: '',
  password: '',
  realName: '',
  phone: '',
  email: '',
  gender: 1,
  address: '',
  practiceScope: '',
  hospitalName: ''
})

const doctorFormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 10, message: '用户名长度必须在3-10位之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 15, message: '密码长度必须在6-15位之间', trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入医生姓名', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  hospitalName: [
    { required: true, message: '请选择所属医院', trigger: 'change' }
  ]
}

const doctorPagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 已删除医生管理相关
const deletedDoctorsDialogVisible = ref(false)
const deletedDoctorsLoading = ref(false)
const deletedDoctorsList = ref([])
const deletedDoctorsPagination = reactive({
  current: 1,
  size: 10,
  total: 0
})



// 活动管理相关
const activityLoading = ref(false)
const activityList = ref([])
const selectedActivities = ref([])
const activityDialogVisible = ref(false)
const isEditActivity = ref(false)
const activitySubmitLoading = ref(false)
const activityFormRef = ref()
const coverUploadRef = ref()
const coverFile = ref(null)

const activitySearchForm = reactive({
  name: '',
  location: '',
  startTime: '',
  endTime: ''
})

const activityForm = reactive({
  id: null,
  name: '',
  cover: '',
  description: '',
  location: '',
  startTime: '',
  endTime: ''
})

const activityFormRules = {
  name: [
    { required: true, message: '请输入活动名称', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入活动描述', trigger: 'blur' }
  ],
  location: [
    { required: true, message: '请输入活动地点', trigger: 'blur' }
  ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ]
}

const activityPagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 管理员信息
const adminInfo = reactive({
  realName: '管理员'
})

// 计算属性
const doctorDialogTitle = computed(() => isEditDoctor.value ? '编辑医生' : '新增医生')
const activityDialogTitle = computed(() => isEditActivity.value ? '编辑活动' : '新增活动')



// 获取医院列表
const fetchHospitalList = async () => {
  try {
    const response = await getHospitalList()
    if (response.code === 200) {
      hospitalList.value = response.data.hospitals || []
    }
  } catch (error) {
    console.error('获取医院列表失败:', error)
    ElMessage.error('获取医院列表失败')
  }
}

// 获取医生列表
const fetchDoctorList = async () => {
  try {
    doctorLoading.value = true
    const queryData = {
      realName: doctorSearchForm.realName,
      phone: doctorSearchForm.phone,
      email: doctorSearchForm.email,
      gender: doctorSearchForm.gender,
      practiceScope: doctorSearchForm.practiceScope,
      level: doctorSearchForm.level,
      current: doctorPagination.current,
      size: doctorPagination.size
    }
    
    const response = await getDoctorsByAdmin(queryData)
    
    if (response.code === 200) {
      doctorList.value = response.data.records
      doctorPagination.total = response.data.total
    } else {
      ElMessage.error(response.message || '获取医生列表失败')
    }
  } catch (error) {
    console.error('获取医生列表失败:', error)
    ElMessage.error('获取医生列表失败，请检查网络连接')
  } finally {
    doctorLoading.value = false
  }
}

// 获取已删除医生列表
const fetchDeletedDoctors = async () => {
  try {
    deletedDoctorsLoading.value = true
    const pageDTO = { 
      current: deletedDoctorsPagination.current, 
      size: deletedDoctorsPagination.size 
    }
    
    const response = await getDeletedDoctorsPage(pageDTO)
    
    if (response.code === 200) {
      deletedDoctorsList.value = response.data.records
      deletedDoctorsPagination.total = response.data.total
    } else {
      ElMessage.error(response.message || '获取已删除医生列表失败')
    }
  } catch (error) {
    console.error('获取已删除医生列表失败:', error)
    ElMessage.error('获取已删除医生列表失败，请检查网络连接')
  } finally {
    deletedDoctorsLoading.value = false
  }
}



// 处理封面URL
const processCoverUrl = (url) => {
  if (!url) return ''
  
  // 如果已经是完整的URL，直接返回
  if (url.startsWith('http://') || url.startsWith('https://')) {
    return url
  }
  
  // 如果是MinIO的URL，直接返回
  if (url.includes('minio')) {
    return url
  }
  
  // 如果是相对路径，添加服务器基础URL
  if (url.startsWith('/')) {
    return `http://localhost:8080${url}`
  }
  
  // 如果URL已经包含了服务器地址，直接返回
  if (url.includes('localhost:8080')) {
    return url
  }
  
  // 根据后端API的配置，使用最可能的路径
  // 通常后端会将上传的文件放在 /uploads 目录下
  // 使用新的封面获取接口
  return `http://localhost:8080/activity/cover/${url}`
}

// 获取活动列表
const fetchActivityList = async () => {
  try {
    activityLoading.value = true
    const response = await getAdminActivityList()
    
    if (response.code === 200) {
      // 调试：打印活动数据
      console.log('活动列表数据:', response.data)
      
      // 处理每个活动的封面URL
      activityList.value = response.data.map(activity => ({
        ...activity,
        cover: processCoverUrl(activity.cover)
      }))
      
      activityPagination.total = response.data.length
    } else {
      ElMessage.error(response.message || '获取活动列表失败')
    }
  } catch (error) {
    console.error('获取活动列表失败:', error)
    ElMessage.error('获取活动列表失败，请检查网络连接')
  } finally {
    activityLoading.value = false
  }
}



// 医生搜索
const handleDoctorSearch = () => {
  doctorPagination.current = 1
  fetchDoctorList()
}

// 重置医生搜索
const resetDoctorSearch = () => {
  Object.assign(doctorSearchForm, {
    realName: '',
    phone: '',
    email: '',
    gender: '',
    practiceScope: '',
    level: '',
    hospitalName: ''
  })
  doctorPagination.current = 1
  fetchDoctorList()
}

// 活动搜索
const handleActivitySearch = () => {
  // 由于后端API没有分页和搜索功能，这里只是简单的客户端过滤
  fetchActivityList()
}

// 重置活动搜索
const resetActivitySearch = () => {
  Object.assign(activitySearchForm, {
    name: '',
    location: '',
    startTime: '',
    endTime: ''
  })
  fetchActivityList()
}



// 医生选择变化
const handleDoctorSelectionChange = (selection) => {
  selectedDoctors.value = selection
}

// 活动选择变化
const handleActivitySelectionChange = (selection) => {
  selectedActivities.value = selection
}

// 显示创建医生对话框
const showCreateDoctorDialog = () => {
  isEditDoctor.value = false
  doctorDialogVisible.value = true
}

// 显示编辑医生对话框
const showEditDoctorDialog = (row) => {
  isEditDoctor.value = true
  Object.assign(doctorForm, row)
  doctorDialogVisible.value = true
}

// 重置医生表单
const resetDoctorForm = () => {
  Object.assign(doctorForm, {
    username: '',
    password: '',
    realName: '',
    phone: '',
    email: '',
    gender: 1,
    address: '',
    practiceScope: '',
    hospitalName: ''
  })
  if (doctorFormRef.value) {
    doctorFormRef.value.resetFields()
  }
}

// 显示创建活动对话框
const showCreateActivityDialog = () => {
  isEditActivity.value = false
  activityDialogVisible.value = true
}

// 显示编辑活动对话框
const showEditActivityDialog = (row) => {
  isEditActivity.value = true
  Object.assign(activityForm, {
    id: row.id,
    name: row.name,
    cover: processCoverUrl(row.cover),
    description: row.description,
    location: row.location,
    startTime: row.startTime,
    endTime: row.endTime
  })
  activityDialogVisible.value = true
}

// 重置活动表单
const resetActivityForm = () => {
  Object.assign(activityForm, {
    id: null,
    name: '',
    cover: '',
    description: '',
    location: '',
    startTime: '',
    endTime: ''
  })
  if (activityFormRef.value) {
    activityFormRef.value.resetFields()
  }
  // 重置封面文件
  coverFile.value = null
  if (coverUploadRef.value) {
    coverUploadRef.value.clearFiles()
  }
}

// 处理封面文件选择
const handleCoverChange = (file) => {
  // 验证文件类型
  const isValidType = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/bmp'].includes(file.raw.type)
  if (!isValidType) {
    ElMessage.error('只支持 jpg, jpeg, png, gif, bmp 格式的图片')
    return false
  }
  
  // 验证文件大小（5MB）
  const isLt5M = file.raw.size / 1024 / 1024 < 5
  if (!isLt5M) {
    ElMessage.error('文件大小不能超过 5MB')
    return false
  }
  
  // 保存文件并显示预览
  coverFile.value = file.raw
  activityForm.cover = URL.createObjectURL(file.raw)
  return false // 阻止自动上传
}

// 提交医生表单
const handleDoctorSubmit = async () => {
  if (!doctorFormRef.value) return
  
  try {
    await doctorFormRef.value.validate()
    doctorSubmitLoading.value = true
    
    let response
    if (isEditDoctor.value) {
      response = await updateDoctor(doctorForm)
    } else {
      response = await createDoctor(doctorForm)
    }
    
    if (response.code === 200) {
      ElMessage.success(isEditDoctor.value ? '更新成功' : '创建成功')
      doctorDialogVisible.value = false
      fetchDoctorList()
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败，请检查网络连接')
  } finally {
    doctorSubmitLoading.value = false
  }
}

// 提交活动表单
const handleActivitySubmit = async () => {
  if (!activityFormRef.value) return
  
  try {
    await activityFormRef.value.validate()
    activitySubmitLoading.value = true
    
    // 验证时间
    if (activityForm.startTime && activityForm.endTime) {
      if (new Date(activityForm.startTime) >= new Date(activityForm.endTime)) {
        ElMessage.error('开始时间不能晚于或等于结束时间')
        return
      }
    }
    
    let response
    if (isEditActivity.value) {
      response = await updateActivity(activityForm)
    } else {
      response = await createActivity(activityForm)
    }
    
    if (response.code === 200) {
      console.log('活动操作成功，响应数据:', response.data)
      
      // 如果有封面文件，上传封面
      if (coverFile.value) {
        try {
          console.log('开始上传封面文件...')
          const uploadResponse = await uploadActivityCover(response.data.id, coverFile.value)
          console.log('封面上传响应:', uploadResponse)
          if (uploadResponse.code === 200) {
            // 更新活动封面URL
            activityForm.cover = uploadResponse.data.coverUrl
            console.log('更新后的封面URL:', activityForm.cover)
            await updateActivity(activityForm)
          }
        } catch (uploadError) {
          console.error('封面上传失败:', uploadError)
          ElMessage.warning('活动创建成功，但封面上传失败')
        }
      } else if (isEditActivity.value && activityForm.cover) {
        // 编辑时，如果没有新文件但有封面URL，确保封面URL被保存
        console.log('编辑模式，保持现有封面URL:', activityForm.cover)
        try {
          await updateActivity(activityForm)
        } catch (updateError) {
          console.error('更新活动封面失败:', updateError)
          ElMessage.warning('活动更新成功，但封面更新失败')
        }
      }
      
      ElMessage.success(isEditActivity.value ? '更新成功' : '创建成功')
      activityDialogVisible.value = false
      fetchActivityList()
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败，请检查网络连接')
  } finally {
    activitySubmitLoading.value = false
  }
}



// 删除医生
const handleDeleteDoctor = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这个医生吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await deleteDoctor(row.id)
    
    if (response.code === 200) {
      ElMessage.success('删除成功')
      fetchDoctorList()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败，请检查网络连接')
    }
  }
}

// 删除活动
const handleDeleteActivity = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这个活动吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await deleteActivity(row.id)
    
    if (response.code === 200) {
      ElMessage.success('删除成功')
      fetchActivityList()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败，请检查网络连接')
    }
  }
}



// 批量删除医生
const handleBatchDeleteDoctor = async () => {
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedDoctors.value.length} 个医生吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const doctorIds = selectedDoctors.value.map(doctor => doctor.id)
    const response = await batchDeleteDoctor(doctorIds)
    
    if (response.code === 200) {
      ElMessage.success('批量删除成功')
      selectedDoctors.value = []
      fetchDoctorList()
    } else {
      ElMessage.error(response.message || '批量删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败，请检查网络连接')
    }
  }
}

// 批量删除活动
const handleBatchDeleteActivity = async () => {
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedActivities.value.length} 个活动吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 逐个删除活动（因为后端没有批量删除接口）
    const deletePromises = selectedActivities.value.map(activity => deleteActivity(activity.id))
    await Promise.all(deletePromises)
    
    ElMessage.success('批量删除成功')
    selectedActivities.value = []
    fetchActivityList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败，请检查网络连接')
    }
  }
}

// 恢复医生
const handleRestoreDoctor = async (doctorId) => {
  try {
    await ElMessageBox.confirm('确定要恢复这个医生吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await restoreDoctor(doctorId)
    
    if (response.code === 200) {
      ElMessage.success('恢复成功')
      fetchDeletedDoctors()
    } else {
      ElMessage.error(response.message || '恢复失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('恢复失败:', error)
      ElMessage.error('恢复失败，请检查网络连接')
    }
  }
}







// 医生分页处理
const handleDoctorSizeChange = (size) => {
  doctorPagination.size = size
  doctorPagination.current = 1
  fetchDoctorList()
}

const handleDoctorCurrentChange = (current) => {
  doctorPagination.current = current
  fetchDoctorList()
}

// 已删除医生分页处理
const handleDeletedDoctorsSizeChange = (size) => {
  deletedDoctorsPagination.size = size
  deletedDoctorsPagination.current = 1
  fetchDeletedDoctors()
}

const handleDeletedDoctorsCurrentChange = (current) => {
  deletedDoctorsPagination.current = current
  fetchDeletedDoctors()
}



// 活动分页处理
const handleActivitySizeChange = (size) => {
  activityPagination.size = size
  activityPagination.current = 1
  // 由于后端API没有分页，这里只是更新本地分页状态
}

const handleActivityCurrentChange = (current) => {
  activityPagination.current = current
  // 由于后端API没有分页，这里只是更新本地分页状态
}



// 查看已删除医生
const showDeletedDoctors = () => {
  deletedDoctorsDialogVisible.value = true
  fetchDeletedDoctors()
}

// 退出登录
const handleLogout = async () => {
  try {
    await ElMessageBox.confirm('确定要退出登录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    localStorage.removeItem('adminToken')
    localStorage.removeItem('level')
    localStorage.removeItem('adminInfo')
    ElMessage.success('已退出登录')
    router.push('/login')
  } catch {
    // 用户取消
  }
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN')
}



// 处理图片加载错误
const handleImageError = (event) => {
  console.error('图片加载失败:', event.target.src)
  
  // 直接显示加载失败
  event.target.style.display = 'none'
  const errorSpan = event.target.parentElement.querySelector('.image-error')
  if (errorSpan) {
    errorSpan.style.display = 'inline'
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchHospitalList()
  fetchDoctorList()
  fetchActivityList()
})
</script>

<style scoped>
.normal-admin-container {
  height: 100vh;
  background-color: #f5f5f5;
}

.header {
  background-color: #fff;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
}

.header-left h2 {
  margin: 0;
  color: #303133;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 15px;
}

.welcome {
  color: #606266;
  font-size: 14px;
}

.main-content {
  padding: 20px;
}

.admin-tabs {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
}

.tab-content {
  margin-top: 20px;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 15px;
}

.search-area {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.action-area {
  display: flex;
  gap: 10px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

:deep(.el-tabs__header) {
  margin-bottom: 0;
}

:deep(.el-tabs__content) {
  padding: 0;
}

.deleted-doctors-content {
  padding: 20px 0;
}

.deleted-doctors-content .pagination {
  margin-top: 20px;
  text-align: right;
}

/* 封面上传样式 */
.cover-upload {
  display: flex;
  align-items: flex-start;
  gap: 20px;
}

.cover-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

.cover-uploader:hover {
  border-color: #409eff;
}

.cover-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 90px;
  line-height: 90px;
  text-align: center;
}

.cover-image {
  width: 120px;
  height: 90px;
  display: block;
  object-fit: cover;
}

.cover-tips {
  flex: 1;
  color: #909399;
  font-size: 12px;
  line-height: 1.5;
}

.cover-tips p {
  margin: 0 0 5px 0;
}
</style> 

